package com.fy.oa.zc.soap.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//import org.apache.commons.logging.LogFactory;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;

import com.fy.oa.zc.exception.FyOAException;

public final class FyOA_SOAPClientImpl implements FyOA_SOAPClient {
	private static final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(FyOA_SOAPClientImpl.class);

	@Override
	public String post(String data, String urlpath, String soapAction) {
		logger.info(data);
		logger.info(urlpath);
		logger.info(soapAction);
		try {
			byte[] sendXML = data.getBytes("utf-8");
			URL url = new URL(urlpath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setRequestProperty("Content-Length", String.valueOf(sendXML.length));
			conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			conn.setRequestProperty("SOAPAction", soapAction);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);

			OutputStream os = conn.getOutputStream();
			os.write(sendXML);
			os.flush();
			os.close();
			StringBuilder sb = new StringBuilder();
			if (conn.getResponseCode() == 200) {
				InputStream is = conn.getInputStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String result = null;
				while ((result = br.readLine()) != null) {
					sb.append(result);
				}
			} else {
				InputStream is = conn.getErrorStream();
				InputStreamReader isr = new InputStreamReader(is, "utf-8");
				BufferedReader br = new BufferedReader(isr);
				String result = null;
				while ((result = br.readLine()) != null) {
					sb.append(result);
				}
			}
			logger.info(sb.toString());
			return sb.toString();
		} catch (MalformedURLException e) {
			throw new FyOAException("访问CRM服务器失败", e);
		} catch (IOException e) {
			throw new FyOAException("访问CRM服务器失败", e);
		} catch (Exception e) {
			throw new FyOAException("访问CRM服务器失败", e);
		}
	}

}
